package com.netstar.request;


import com.netstar.jsonparser.AbstractParser;
import com.netstar.jsonparser.ParserFactory;
import com.netstar.property.ServerError;
import com.netstar.util.EvtLog;

public abstract class DataRequest extends BaseRequest {

	public abstract void onSuccess(String data);

	@Override
	protected void onHttpComplete(HttpRequest request) {
		final String response = (String) request.getResponse();
		final int code = request.getResponseCode();
		EvtLog.i("NetService", getFinalUrl());
		// DebUtils.i("NetService", "parameters " + getData());
		// DebUtils.i("NetService", "response code " + code + ", response is "
		// + response);
		if (code >= 400 && code <= 499) {
			/*
			 * For 4xx response code, the server will set the error message.
			 */
			AbstractParser parser = ParserFactory.createParser(
					ParserFactory.TYPE_ERROR, response);
			ServerError se = null;
			try {
				se = (ServerError) parser.parse();
			} catch (Exception e) {
				onFail(response);
				return;
			}
			if (null != se) {
				onFail(se.errorDetail);
			} else {
				onFail(FAIL_MSG_PARSE_SERVER_ERROR);
			}
		} else if (200 == code) {
			onSuccess(response);
		} else {
			// For other response code, we simply mark error
			onFail("Server responsed with code " + code);
		}
	}
}
